<template>
  <div
    style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center"
  >
    <el-segmented
      v-model="segmentedValue"
      :options="currentOptions"
      :size="componentProps.size"
      :disabled="componentProps.disabled"
      @change="handleChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElSegmented } from 'element-plus';
import { useAutoDataBinding } from '@/composables/use-data-binding';
import { shouldUpdateChartData } from '@/utils/shallow-equal';
import type { IDataBindingConfig } from '@/components/mt-edit/store/types';

interface SegmentedOption {
  label: string;
  value: string | number;
  disabled?: boolean;
}

const props = defineProps({
  // 数据绑定配置
  dataBinding: {
    type: Object as () => IDataBindingConfig,
    default: () => ({
      enabled: false,
      sourceId: '',
      dataPointId: '',
      targetProperty: 'options',
      transform: 'array',
      defaultValue: '[]',
      updateInterval: 0,
      updateMode: 'replace'
    })
  },
  modelValue: {
    type: [String, Number],
    default: 'option1'
  },
  options: {
    type: Array as () => (string | SegmentedOption)[],
    default: () => [
      { label: '选项一', value: 'option1' },
      { label: '选项二', value: 'option2' },
      { label: '选项三', value: 'option3' }
    ]
  },
  size: {
    type: String as () => 'large' | 'default' | 'small',
    default: 'default'
  },
  disabled: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue', 'change']);

// 响应式属性对象（用于数据绑定）
const componentProps = ref({
  modelValue: props.modelValue,
  options: props.options,
  size: props.size,
  disabled: props.disabled
});

// 使用数据绑定
const shouldUseDataBinding =
  props.dataBinding && props.dataBinding.enabled && props.dataBinding.targetProperty !== 'hide';
const dataBinding = useAutoDataBinding(
  shouldUseDataBinding ? props.dataBinding : null,
  componentProps.value,
  (property: string, value: any) => {
    // 直接更新响应式对象的属性
    if (componentProps.value.hasOwnProperty(property)) {
      (componentProps.value as any)[property] = value;
    }
  }
);

// 监听数据绑定的值变化
// 性能优化：使用浅比较避免不必要的重新渲染
watch(
  () => dataBinding.currentValue.value,
  (newValue, oldValue) => {
    // 如果数据绑定启用且有新值，更新组件属性
    if (shouldUseDataBinding && newValue !== undefined) {
      // 确保数据是数组格式
      let optionsData = newValue;
      if (!Array.isArray(optionsData)) {
        if (typeof optionsData === 'string') {
          try {
            optionsData = JSON.parse(optionsData);
          } catch (e) {
            optionsData = [];
          }
        } else if (typeof optionsData === 'object' && optionsData !== null) {
          // 如果是对象，转换为数组
          optionsData = Object.values(optionsData);
        } else {
          optionsData = [];
        }
      }

      // 性能优化：使用浅比较检查数据是否真的发生变化
      if (shouldUpdateChartData(optionsData, componentProps.value.options)) {
        componentProps.value.options = optionsData;
      }
    }
  },
  { immediate: true, deep: false }
);

// 监听连接状态变化
// 性能优化：添加相等性检查避免不必要的副作用
watch(
  () => dataBinding.isConnected.value,
  (newValue, oldValue) => {
    if (newValue === oldValue) return;
    // 连接状态变化的处理逻辑（如果需要）
  },
  { immediate: true }
);

// 监听props变化，同步到响应式属性对象
// 性能优化：基本类型属性添加相等性检查
watch(
  () => props.modelValue,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      componentProps.value.modelValue = newValue;
    }
  }
);
// 性能优化：基本类型属性添加相等性检查
watch(
  () => props.size,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      componentProps.value.size = newValue;
    }
  }
);
// 性能优化：基本类型属性添加相等性检查
watch(
  () => props.disabled,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      componentProps.value.disabled = newValue;
    }
  }
);
// 性能优化：使用浅比较检查数组数据变化
watch(
  () => props.options,
  (newValue, oldValue) => {
    if (!shouldUseDataBinding && shouldUpdateChartData(newValue, oldValue)) {
      componentProps.value.options = newValue;
    }
  },
  { deep: false }
);

// 使用计算属性来获取当前的选项数据
const currentOptions = computed(() => {
  if (shouldUseDataBinding && dataBinding.currentValue.value !== undefined) {
    let data = dataBinding.currentValue.value;

    // 确保数据是数组格式
    if (!Array.isArray(data)) {
      if (typeof data === 'string') {
        try {
          data = JSON.parse(data);
        } catch {
          data = [];
        }
      } else if (typeof data === 'object' && data !== null) {
        data = Object.values(data);
      } else {
        data = [];
      }
    }

    return data;
  } else {
    return componentProps.value.options;
  }
});

const segmentedValue = ref(props.modelValue);

// 性能优化：基本类型属性添加相等性检查
watch(
  () => props.modelValue,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      segmentedValue.value = newValue;
    }
  }
);

const handleChange = (value: string | number) => {
  emit('update:modelValue', value);
  emit('change', value);
};
</script>
